import {Injectable} from '@angular/core';
import {ActionSheetController} from 'ionic-angular';
import {FileTransfer, FileTransferObject, FileUploadOptions} from "@ionic-native/file-transfer";
import {File} from "@ionic-native/file";
import {Camera, CameraOptions} from "@ionic-native/camera";
import {AppGlobal} from "./app.service";
import {AppConfig} from "../../app/app.config";
import { normalizeURL } from 'ionic-angular';

//import {ImagePicker} from "@ionic-native/image-picker";

@Injectable()
export class UploadService {

  fileTransfer: FileTransferObject;

  // 调用相机时传入的参数
  private cameraOpt:CameraOptions = {
    quality: 50,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.CAMERA,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
    allowEdit: true,
    correctOrientation: true,
    saveToPhotoAlbum: true
  };

  // 调用相册时传入的参数（暂时不用）
  // private imagePickerOpt = {
  //   maximumImagesCount: 6,//选择一张图片
  //   width: 800,
  //   height: 800,
  //   quality: 80,
  //   outputType:0
  // };

  //文件上传参数
  uploadOptions:FileUploadOptions = {
    fileKey: 'file',
    headers: {
      'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'//不加入会发生错误
    },
    params: {}
  };

  upload: any= {
    fileName: 'imageName.jpg',
    successCallback: (data)=> { },//图片上传成功后的回调
    errorCallback: (err)=> { },//图片上传失败后的回调
    listen: ()=> { },//监听上传过程
    saveInLocal:true, //是否复制文件到本地目录
    newFileName:"imageName.jpg" //复制后的文件名，saveInLocal为true时有效
  };

  constructor(private transfer: FileTransfer,
              private file: File,
              private actionSheetCtrl:ActionSheetController,
              private camera:Camera
              //private imagePicker:ImagePicker
  ) {
    this.fileTransfer = this.transfer.create();
  }


  //选择
  showPicActionSheet() {
    let actionSheet=
      this.actionSheetCtrl.create({
        title: '请选择',
        buttons: [
          {
            text: '拍照',
            handler: ()=> {
              this.cameraOpt.sourceType = this.camera.PictureSourceType.CAMERA;
              this.startCamera();
            }
          },
          {
            text: '从手机相册选择',
            handler: ()=> {
              this.cameraOpt.sourceType = this.camera.PictureSourceType.PHOTOLIBRARY;
              this.startCamera();
            }
          },
          {
            text: '取消',
            role: 'cancel',
            handler: ()=> {
            }
          }
        ]
      });
    actionSheet.present();
  }

  // 启动拍照功能
  private startCamera() {
    this.camera.getPicture(this.cameraOpt).then((imageData)=>
    {
      console.log("imageData:"+imageData);
      this.uploadImg(imageData);

      if(this.upload.saveInLocal){
        //将文件移动到本地的应用目录savePath
        //file:///storage/emulated/0/Android/data/ionic.starter/cache/.Pic.jpg?1523169267937

        let orginFilePath = imageData.substr(0,imageData.lastIndexOf('\/')+1);//原始文件目录
        let orginFileName = imageData.substr(imageData.lastIndexOf('\/')+1);//原始文件名
        if(orginFileName.lastIndexOf('?')>0){
          orginFileName = orginFileName.substr(0,orginFileName.lastIndexOf('?'));
        }
        let newFileName = this.upload.newFileName;

        this.file.moveFile(orginFilePath,orginFileName,AppGlobal.savePath,newFileName).then((data)=>{
          //alert("复制文件成功："+JSON.stringify(data));
        },(err)=>{
          //alert("复制文件失败："+JSON.stringify(err));
        }).catch((err)=>{
          //alert("复制文件失败："+JSON.stringify(err));
        })
      }

    }, (err)=>{
      alert('ERROR:'+ err);
      //this.noticeSer.showToast('ERROR:'+ err);//错误：无法使用拍照功能！
    });
  }

// 打开手机相册
//   private openImgPicker() {
//     let temp = '';
//     // this.imagePicker.getPictures(this.imagePickerOpt)
//     //   .then((results)=> {
//     //     for (var i=0; i < results.length; i++) {
//     //       temp += "-"+results[i];
//     //       //alert("pic uri:"+temp);
//     //     }
//     //     alert("temp:"+temp);
//     //     //this.uploadImg(temp);
//     //   }, (err)=> {
//     //     alert('ERROR:'+ err);
//     //     //this.noticeSer.showToast('ERROR:'+ err);//错误：无法从手机相册中选择图片！
//     //   });
//   }


// 上传图片
  private uploadImg(path:string) {
    if (!path) {
      return;
    }

    this.fileTransfer.upload(path, AppConfig.ServerDomain+AppConfig.UploadContext, this.uploadOptions)
      .then((data)=> {
        //构造返回对象，将path放入返回对象内
        let resObject = JSON.parse(data.response);
        resObject.localPath = path;

        if (this.upload.successCallback) {
          alert("上传成功，开始回调！");
          this.upload.successCallback(resObject);
        }
      }, (err) => {
        if (this.upload.errorCallback) {
          this.upload.errorCallback(err);
        } else {
          alert("错误：上传失败！");
          //this.noticeSer.showToast('错误：上传失败！');
        }
      }).catch(err => {alert(err)});
  }

  // 停止上传
  stopUpload() {
    if (this.fileTransfer) {
      this.fileTransfer.abort();
    }
  }

  /**
   * 弹出选项框开始上传图片
   * @param successCallback 上传成功后的回调函数
   * @param errorCallback   上传失败后的回调函数
   * @param {boolean} saveInLocal 是否缓存上传图片到本地目录
   */
  startUploadImg(successCallback,errorCallback,saveInLocal?,newFileName?) {
    this.upload.successCallback = successCallback;
    this.upload.errorCallback = errorCallback;
    if(saveInLocal){
      this.upload.saveInLocal = saveInLocal;
    }
    if(newFileName){
      this.upload.newFileName = newFileName;
    }
    this.showPicActionSheet();
  }
}
